package com.shu.juc;

import java.util.Collections;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.*;

/**
 * @author ssm
 * @version V1.0
 * @description:
 * @date 2020/7/30 10:19
 */

public class CompletableFutureTest2 {

    private final CompletableFuture<Void> completableFuture= new CompletableFuture<Void>();

    public static void main(String[] args) throws InterruptedException {
        CompletableFutureTest2 test = new CompletableFutureTest2();
        System.out.println(test.getPrices());
    }

    private Set<Integer> getPrices() throws InterruptedException {
        Set<Integer> prices = Collections.synchronizedSet(new HashSet<Integer>());
        CompletableFuture<Void> completableFuture1 = CompletableFuture.runAsync(new Task(1, prices));
        CompletableFuture<Void> completableFuture2 = CompletableFuture.runAsync(new Task(2, prices));
        CompletableFuture<Void> completableFuture3 = CompletableFuture.runAsync(new Task(3, prices));

        CompletableFuture<Void> allOf = CompletableFuture.allOf(completableFuture1, completableFuture2, completableFuture3);

        try {
            allOf.get(3,TimeUnit.SECONDS);
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }

        return prices;
    }


    static class Task implements Runnable {
        Integer productId;
        Set<Integer> prices;

        public Task(Integer productId, Set<Integer> prices) {
            this.productId = productId;
            this.prices = prices;
        }

        @Override
        public void run() {
            try {
                Thread.sleep(2000);
                prices.add(new Random().nextInt());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
